/*
 * marketsim-eclipsetrader
 *
 * Copyright (C) 2008-2011 Steve Phelps and John Cartlidge
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 */
/*
 *  (C) Victria Ltd. 2007
 */
package victria.marketsim.bot;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import victria.marketsim.bot.event.BotContainerStartedEvent;
import victria.marketsim.bot.event.BotContainerStoppedEvent;
import victria.marketsim.bot.event.BotEvent;
import victria.marketsim.bot.event.BotEventListener;

import victria.marketsim.core.MarketService;

public class BotContainer implements Serializable {

	protected List<AbstractBot> bots;
	
	protected List<Thread> threads;
	
	protected MarketService marketService;
	
	protected List<BotEventListener> listeners;
	
	protected boolean running = false;
	
	public BotContainer() {
		listeners = new LinkedList<BotEventListener>();
	}
	
	public void startBots() {
		running = true;
		threads = new LinkedList<Thread>();
		for(AbstractBot bot : bots) {
			bot.setParent(this);
			marketService.registerTrader(bot.getBotId());
			Thread botThread = new Thread(bot);
			threads.add(botThread);
			botThread.start();
		}
		fireEvent(new BotContainerStartedEvent(this));
	}
	
	public void stopBots() {
		for(AbstractBot bot : bots) {
			bot.stop();
		}	
		running = false;
		fireEvent(new BotContainerStoppedEvent(this));
	}
	
	public void fireEvent(BotEvent event) {
		for(BotEventListener listener : listeners) {
			listener.eventOccurred(event);
		}
	} 
	
	public void addListener(BotEventListener listener) {
		if (! listeners.contains(listener)) {
			listeners.add(listener);
		}
	}

	public List<AbstractBot> getBots() {
		return bots;
	}

	public void setBots(List<AbstractBot> bots) {
		this.bots = bots;
	}

	public MarketService getMarketService() {
		return marketService;
	}

	public void setMarketService(MarketService marketService) {
		this.marketService = marketService;
	}

	public boolean isRunning() {
		return running;
	}
	
	
	
}
